@REM 添加 Git Commit 信息

@echo off

SETLOCAL
set input_file=%~1

call %g_bat_dir_path%\readini.bat %g_config_file_path% option isAddGitCommit isAddGitCommit

@if not defined isAddGitCommit (
	@echo Warning: .ini file [option: isAddGitCommit] does not set param
	exit /B 0
)

@if %isAddGitCommit% equ 0 (
	@exit /B 0
)

@REM 判断 git 是否安装
call :checkGitInstall

@if not %errorlevel% equ 0 (
    echo Error: git is not install
	exit /B 1
)

@REM 检测是否为 git 仓库
call :checkgitInit

@if not %errorlevel% equ 0 (
    echo Error: not a git repository
	exit /B 1
)

call %g_bat_dir_path%\readini.bat %g_config_file_path% git_commit addr start_addr
call %g_bat_dir_path%\readini.bat %g_config_file_path% git_commit size size

@if not defined start_addr (
	@echo Error: .ini file [git_commit: addr] does not set param
	exit /B 1
)

@if not defined size (
	@echo Error: .ini file [git_commit: size] does not set param
	exit /B 1
)

@for /F %%i in ('git symbolic-ref --short -q HEAD') do @set branchid=%%i
@for /F %%i in ('git rev-parse --short HEAD') do @set commitid=%%i
@set commitchage=_test

@REM 判断源码文件是否有改动
@for /F %%i in ('git status -s ^| findstr \.c$') do @set cfile=%%i
@for /F %%i in ('git status -s ^| findstr \.h$') do @set hfile=%%i
@for /F %%i in ('git status -s ^| findstr \.cpp$') do @set cppfile=%%i
@for /F %%i in ('git status -s ^| findstr \.hpp$') do @set hppfile=%%i

@if  "%cfile%" == "" (
	@if  "%hfile%" == "" (
		@if  "%cppfile%" == "" (
			@if  "%hppfile%" == "" (
				@set commitchage=
			)
		)
	)
)

@set strGitCommit=%branchid%_%commitid%%commitchage%
@echo strGitCommit=%strGitCommit%

call %g_bat_dir_path%\vstr_len.bat %strGitCommit% str_len

@if %str_len% geq %size% (
	@echo Error: size[%str_len%] over %size%, error exit
	@exit /B 1
)

@set /a end_addr=%start_addr%+%str_len%
@set output_file=git_%input_file%
set input_file_name=%input_file%.hex
set output_file_name=%output_file%.hex

%g_exe_dir_path%\srec_cat.exe -generate %start_addr% %end_addr% -repeat-string %strGitCommit% %g_obj_dir_path%\%input_file_name% -intel -exclude %start_addr% %end_addr% -o %g_obj_dir_path%\%output_file_name% -intel
@echo %input_file_name% add git commit info generate %output_file_name%

(endlocal
set %~2=%output_file%
)
ENDLOCAL

exit /B 0


@REM 检测 git 是否安装
:checkGitInstall
@for /f "delims=" %%i in ('git version ^| findstr "version"') do @set gitversion=%%i
@if not "%gitversion%" == "" (
    exit /b 0
)
exit /b 1

@REM 检测是否为 git 仓库
:checkgitInit
@for /f "delims=" %%i in ('git status ^| findstr "branch"') do @set gitcommit=%%i
@if not "%gitcommit%" == "" (
    exit /b 0
)
exit /b 1
